package com.bw.house.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.house.mapper.TbResourceMapper;
import com.bw.po.TbHouseExamine;
import com.bw.house.service.TbHouseExamineService;
import com.bw.house.mapper.TbHouseExamineMapper;
import com.bw.po.TbResource;
import com.bw.result.ResponseState;
import com.bw.result.ResultVo;
import com.bw.vo.IdVo;
import com.bw.vo.TbHouseExamineSearchVo;
import com.bw.vo.TbHouseExamineVo;
import com.bw.vo.TbHouseInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 花开Mystic
* @description 针对表【tb_house_examine(房源审核表)】的数据库操作Service实现
* @createDate 2023-11-12 20:04:40
*/
@Service
@Slf4j
public class TbHouseExamineServiceImpl extends ServiceImpl<TbHouseExamineMapper, TbHouseExamine>
    implements TbHouseExamineService{

    @Autowired
    private TbHouseExamineMapper tbHouseExamineMapper;

    @Autowired
    private TbResourceMapper tbResourceMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Override
    public ResultVo listBySearchVo(TbHouseExamineSearchVo tbHouseExamineSearchVo) {
        Page<TbHouseExamine> page = new Page<>(tbHouseExamineSearchVo.getPageNum(), tbHouseExamineSearchVo.getPageSize());
        Page<TbHouseExamineVo> examineVoPage = tbHouseExamineMapper.listBySearchVo(page,tbHouseExamineSearchVo);
        //获取初始的集合
        List<TbHouseExamineVo> beforeList = examineVoPage.getRecords();
        //为初始的集合添加房产图片集数据
        beforeList.forEach(item->{
            QueryWrapper<TbResource> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(TbResource::getResourceId,item.getResourceId());
            List<TbResource> resources = tbResourceMapper.selectList(wrapper);
            ArrayList<String> list = new ArrayList<>();
            for (TbResource resource : resources) {
                list.add(resource.getUrl());
            }
            item.setImgList(list);
        });
        //重新set赋值Records
        examineVoPage.setRecords(beforeList);
        return ResultVo.SUCCESS(examineVoPage);
    }

    @Override
    public ResultVo updateByVo(TbHouseExamineVo tbHouseExamineVo) {
        String xmlFile = "processes/houseExamine.bpmn20.xml";
        String pngFile = "processes/houseExamine.bpmn20.png";
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource(xmlFile)
                .addClasspathResource(pngFile)
                .name("审核房源")
                .deploy();
        log.info("流程部署:"+deployment.getName());

        String processDefinitionKey = "houseExamine";
        String businessKey = tbHouseExamineVo.getId();
        Map<String, Object> variables = new HashMap<>();//examinePerson
        variables.put("examinePerson","当前登录人");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, variables);
        System.out.println("流程实例ID:"+processInstance.getProcessInstanceId());

        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
        if(task == null){
            return ResultVo.FAILED(ResponseState.NOT_EXIST);
        }
        taskService.setVariable(task.getId(),"status",tbHouseExamineVo.getStatus());
        taskService.complete(task.getId());
        Task getTask = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
        if(getTask != null){
            System.out.println("流程执行失败");
            return ResultVo.FAILED(ResponseState.ERROR);
        }
        TbHouseExamine houseExamine = new TbHouseExamine();
        BeanUtils.copyProperties(tbHouseExamineVo,houseExamine);
        boolean update = updateById(houseExamine);
        return update?ResultVo.SUCCESS():ResultVo.FAILED(ResponseState.ERROR);
    }

    @Override
    public ResultVo getExamineHouseDetail(IdVo idVo) {
        // 根据审核id查询房源详情
        TbHouseInfoVo tbHouseInfoVo = tbHouseExamineMapper.getExamineHouseDetail(idVo);
        QueryWrapper<TbResource> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbResource::getResourceId,tbHouseInfoVo.getResourceId());
        List<TbResource> resources = tbResourceMapper.selectList(wrapper);
        ArrayList<String> list = new ArrayList<>();
        for (TbResource resource : resources) {
            list.add(resource.getUrl());
        }
        tbHouseInfoVo.setResource(list);
        return ResultVo.SUCCESS(tbHouseInfoVo);
    }

    @Override
    public ResultVo examineByActiviti(TbHouseExamineVo tbHouseExamineVo) {
        String xmlFile = "processes/houseExamine.bpmn20.xml";
        String pngFile = "processes/houseExamine.bpmn20.png";
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource(xmlFile)
                .addClasspathResource(pngFile)
                .name("审核房源")
                .deploy();
        log.info("流程部署:"+deployment.getName());

        String processDefinitionKey = "houseExamine";
        String businessKey = tbHouseExamineVo.getId();
        Map<String, Object> variables = new HashMap<>();//examinePerson
        variables.put("examinePerson","当前登录人");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, variables);
        System.out.println("流程实例ID:"+processInstance.getProcessInstanceId());

        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
        if(task == null){
            return ResultVo.FAILED(ResponseState.NOT_EXIST);
        }
        taskService.setVariable(task.getId(),"status",tbHouseExamineVo.getStatus());
        taskService.complete(task.getId());
        Task getTask = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
        if(getTask != null){
            System.out.println("流程执行失败");
            return ResultVo.FAILED(ResponseState.ERROR);
        }
        return ResultVo.SUCCESS();
    }
}




